﻿/** DETAILS AND USAGE INSTRUCTIONS ^
 * 
 * @class: com.singlenotion.net.RemotingService
 * @copyright: (c) Copyright 2009 Single Notion.
 * @tiptext: Basic class for AS3 AMFPHP Remoting
 * 
 * @language: Actionscript 3
 * 
 * @author: Adam Jowett
 * @company: Single Notion
 * @link: http://www.singlenotion.com
 * 
 * @created: 10/06/2009
 * @modified: 22/06/2009
 * @version: 1.1
 * 
 * @description:	
 * 
 * @usage:
 * 
 * 		To access backend via remoting do the following:
 * 
 * 		import com.singlenotion.net.RemotingService;
 * 		
 * 		public class RemotingTest
 * 		{
 * 			public var _service:RemotingService;
 * 			
 * 			public function RemotingTest ()
 * 			{
 * 				init();
 * 			}
 * 
 * 			public function init ():void
 * 			{
 * 				_service = new RemotingService("http://somewhere.com/amfphp/gateway.php");
 * 				_service.addEventListener(RemotingService.RESULT_RECEIVED, onResult, false, 0, true);
 * 				_service.addEventListener(RemotingService.FAULT_RECEIVED, onFault, false, 0, true);
 * 
 * 				var params:Object = {arg1:"something",arg2:"2"};
 * 				_service.callMethod("Class.method", params);
 * 				_service.callMethod("Class.method", param1, param2, param3);
 * 			}
 * 			
 * 			private function onResult($result:*):void
 * 			{
 * 			}
 * 
 * 			private function onFault($fault:*):void
 * 			{
 * 			}
 * 		}
 * 
 * @parameter: 		gateway:String - URL of gateway.php file
 * @parameter:		encoding:ObjectEncoding - Optional parameter to change the AMF encoding type (defaults to AMF0)
 * 
 * @returns:		nothing.
 * 
 */

package com.singlenotion.net 
{
	import flash.events.Event;
	import flash.net.NetConnection;
	import flash.net.ObjectEncoding;
	import flash.net.Responder;
	
	public class RemotingService extends NetConnection
	{
		public static const RESULT_RECEIVED:String = "resultReceived";
		public static const FAULT_RECEIVED:String = "faultReceived";
		
		public var result:*;
		public var fault:*;
		
		private var _responder:Responder;
		
		public function RemotingService($gateway:String, $encoding:int = ObjectEncoding.AMF0) 
		{
			objectEncoding = $encoding;
			connect($gateway);
			
			_responder = new Responder(onResult, onFault);
		}
		
		private function onResult($result:*):void
		{
			fault = null;
			result = $result;
			dispatchEvent(new Event(RemotingService.RESULT_RECEIVED, true, true));
		}
		
		private function onFault($fault:*):void
		{
			result = null;
			fault = $fault;
			dispatchEvent(new Event(RemotingService.FAULT_RECEIVED, true, true));
		}
		
		public function get responder():Responder { return _responder; }
	}
}